<template>
  <div id="goodslist">
    <a-card style="marginbottom: 10px">
      <div :style="{ 'margin-bottom': '20px', dsplay: 'flex' }">
        <!-- <a-button type="primary" :style="{'margin-right':'10px'}" @click="toAdd"> 添加商品 </a-button> -->
        <a-cascader
          :options="options"
          :field-names="{ label: 'typeName', value: 'typeId', children: 'items' }"
          :load-data="loadData"
          placeholder="选择分类"
          change-on-select
          @change="onChange"
        />
      </div>
      <a-table :pagination="pagination" :columns="columns" :data-source="data" :rowKey="(record) => record.goodsId">
        <span slot="goodsStatus" slot-scope="text, record">
          <a-switch
            checked-children="上架"
            un-checked-children="下架"
            :checked="record.goodsStatus === 1"
            @change="changeStatus(record)"
            :loading="false"
          />
        </span>
 
        <span @click="showModal(record)" slot="action" slot-scope="text, record">
          <a>修改商品信息</a>
        </span>
      </a-table>
    </a-card>
    <a-modal
      title="修改信息"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleSubmit"
      @cancel="visible = false"
    >
      <a-form id="components-form-demo-validate-other" :form="form" v-bind="formItemLayout" @submit="handleSubmit">
        <a-form-item label="分类" has-feedback>
          <a-select
            v-decorator="[
              'goodsType',
              { initialValue: this.tochange.goodsType },
              { rules: [{ required: true, message: '请选择一个分类!' }] },
            ]"
            placeholder="请选择一个分类"
          >
            
            <a-select-option v-for="(item, index) in options" :key="index" :value="item.typeId">{{
              item.typeName
            }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="品牌" has-feedback>
          <a-select
            v-decorator="[
              'goodsBrand',
              { initialValue: this.tochange.goodsBrand },
              { rules: [{ required: true, message: '请选择一个品牌!' }] },
            ]"
            placeholder="请选择一个品牌"
          >
            <a-select-option v-for="(item, index) in brand" :key="index" :value="item.orginId">{{
              item.orginName
            }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="商品名称">
          <a-input
            v-decorator="[
              'goodsName',
              { initialValue: this.tochange.goodsName },
              { rules: [{ required: true, message: '请填写商品名称' }] },
            ]"
          />
        </a-form-item>

        <a-form-item label="进价">
          <a-input-number
            v-decorator="[
              'goodsPrice',
              { initialValue: this.tochange.goodsPrice },
              { rules: [{ required: true, message: '请填写商品进价' }] },
            ]"
            :min="1"
          />
          <span class="ant-form-text"> ￥ </span>
        </a-form-item>

        <a-form-item label="售价">
          <a-input-number
            v-decorator="[
              'goodsSellingPrice',
              { initialValue: this.tochange.goodsSellingPrice },
              { rules: [{ required: true, message: '请填写商品售价' }] },
            ]"
            :min="1"
          />
          <span class="ant-form-text"> ￥ </span>
        </a-form-item>

        <a-form-item label="库存">
          <a-input-number
            v-decorator="[
              'goodsCount',
              { initialValue: this.tochange.goodsCount },
              { rules: [{ required: true, message: '请填写商品库存' }] },
            ]"
            :min="1"
          />
          <span class="ant-form-text"> 件 </span>
        </a-form-item>

        <a-form-item label="来源地">
          <a-input
            v-decorator="[
              'goodsOrgin',
              { initialValue: this.tochange.goodsOrgin },
              { rules: [{ required: true, message: '请填写来源地' }] },
            ]"
          />
        </a-form-item>

        <a-form-item label="商品描述">
          <a-textarea
            placeholder="商品描述"
            v-decorator="[
              'goodsDescribed',
              { initialValue: this.tochange.goodsDescribed },
              { rules: [{ required: true, message: '请填写来源地' }] },
            ]"
          />
        </a-form-item>

        <!-- <a-form-item label="上下架">
          <a-switch
            checked-children="上架"
            un-checked-children="下架"
            defaultChecked:this.tochange.goodsStatus
            v-decorator="['goodsStatus', { valuePropName: 'checked' }]"
          />
        </a-form-item> -->
        <a-form-item label="图片" extra="">
          <a-upload
          class="upload-list-inline"
            v-decorator="['goodsImg']"
            action="/api/adminGoodsOperation/upFile"
            list-type="picture"
            :default-file-list="defaultFileList"
            @change="handleChange"
            @preview="handlePreview"
          >
            <a-button v-if="defaultFileList.length < 1"> <a-icon type="upload" /> Upload </a-button>
          </a-upload>
        </a-form-item>
        <!-- <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
          <a-button type="primary" html-type="submit"> Submit </a-button>
        </a-form-item> -->
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import Vue from 'vue'
import { Cascader } from 'ant-design-vue'
import {
  AdminQueryAllGoods,
  queryParentGoods,
  querySomeGoodsByType,
  deleteGoods,
  putUpGoods,
  addGoods,
  queryOrgin,
  updateGoods,
} from '@/api/goods'
const columns = [
  {
    title: '图片',
    dataIndex: 'goodsImg',
    key: 'goodsImg',
    scopedSlots: { customRender: 'goodsImg' },
  },
  {
    title: '商品名称',
    dataIndex: 'goodsName',
    key: 'goodsName',
  },
  {
    title: '商品ID',
    dataIndex: 'goodsId',
    key: 'goodsId',
  },
  {
    title: '销售价',
    dataIndex: 'goodsSellingPrice',
    key: 'goodsSellingPrice',
  },
  {
    title: '入库时间',
    dataIndex: 'goodsPutaway',
    key: 'goodsPutaway',
  },
  {
    title: '货源地',
    dataIndex: 'goodsOrgin',
    key: 'goodsOrgin',
  },
  {
    title: '状态',
    key: 'goodsStatus',
    dataIndex: 'goodsStatus',
    scopedSlots: { customRender: 'goodsStatus' },
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
]
Vue.use(Cascader)
export default {
  data() {
    return {
      visible: false,
      confirmLoading: false,
      // 选中要修改的信息
      tochange: {},
      defaultFileList: [],
      // 分类信息
      data: [],
      columns,
      pagination: {
        pageNum: 1,
        pageSize: 10,
      },
      options: [],
      formItemLayout: {
        labelCol: { span: 7 },
        wrapperCol: { span: 8 },
      },
      goodsType: [],
      brand: [],
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'validate_other' })
  },
  methods: {
    init() {
      let params = {
        pageNum: 1,
        pageSize: 10,
      }
      // 获取初始全部商品 第一页
      AdminQueryAllGoods({ ...params })
        .then((res) => {
          this.data = res.data.list
        })
        .catch((err) => {
          console.log(err)
        })
      // 获取所有父级分类
      queryParentGoods({})
        .then((res) => {
          this.options = res.data
        })
        .catch((err) => {
          console.log(err)
        })
      queryOrgin({})
        .then((res) => {
          this.brand = res.data
          console.log(this.brand)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 选择分类
    onChange(value) {
      console.log(value)
      let params = {
        goodsType: value[0],
        pageNum: 1,
        pageSize: 10,
      }
      querySomeGoodsByType({ ...params })
        .then((res) => {
          this.data = res.data.list
        })
        .catch((err) => {
          console.log(err)
        })
    },
    loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true

      // load options lazily
      setTimeout(() => {
        targetOption.loading = false
        targetOption.children = [
          {
            label: `${targetOption.label} Dynamic 1`,
            value: 'dynamic1',
          },
          {
            label: `${targetOption.label} Dynamic 2`,
            value: 'dynamic2',
          },
        ]
        this.options = [...this.options]
      }, 1000)
    },
    changeStatus(value) {
      this.data.map((item) => {
        if (item.goodsId === value.goodsId) {
          if (item.goodsStatus === 1) {
            item.goodsStatus = 0
            // 下架
            deleteGoods({ goodsId: item.goodsId })
              .then((res) => {
                console.log(res)
                item.goodsStatus = 0
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            // 上架
            item.goodsStatus = 1
            putUpGoods({ goodsId: item.goodsId })
              .then((res) => {
                console.log(res)
                item.goodsStatus = 1
              })
              .catch((err) => {
                console.log(err)
              })
          }
        }
      })
    },
    toAdd() {
      console.log('添加商品')
    },
    // 选中修改商品信息
    showModal(value) {
      this.visible = true
      // this.defaultFileList = [];
      
      // console.log(value)
      this.tochange = {}
      this.tochange = value
      let object = {
        name:this.tochange.goodsImg,
        status: 'done',
        uid : this.tochange.id,
        url:'http://127.0.0.1:80/' + this.tochange.goodsImg,
        thumbUrl:'http://127.0.0.1:80/' + this.tochange.goodsImg
      }
      this.defaultFileList[0] = object
      console.log(this.defaultFileList,object)
      // this.defaultFileList[0].url = 'http://3s80z99705.zicp.vip' + this.tochange.goodsImg
      // console.log(this.defaultFileList)
    },
    handleOk(e) {
      this.handleSubmit(e)
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
    },
    handleChange({ file, fileList }) {
      console.log(file, fileList,this.defaultFileList);
      if (file.status !== 'uploading') {
        this.defaultFileList = fileList
      }
    },
    handlePreview({ file, fileList }){
      console.log(file, fileList)
    },
    handleSubmit(e) {
      console.log(this.tochange)
      this.confirmLoading = true;
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values)
          if(!values.goodsImg ){
            values.goodsImg = this.tochange.goodsImgs
          }else{
            values.goodsImg = values.goodsImg.file.name
          }
          console.log(values)
          values.id = this.tochange.id
          updateGoods({
            ...values
          }).then((res) =>{
            if(res.code ==200 ){
              this.$notification.success({
                message: res.message,
              });
              this.visible = false;
              this.confirmLoading = false;
              this.tochange = {}
            }else{
              this.$notification.error({
                message: res.message,
              });
            }
          }).catch((err) =>{
            console.log(err)
          })
        }
      })
    },
    normFile(e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
  },
  created() {
    this.init()
  },
}
</script>

<style scoped>
.goodsImg {
  width: 100px;
  height: 100px;
}
</style>